package com.kfyang.manualgear.daoplugin.injector;

import com.intellij.lang.injection.general.Injection;
import com.intellij.lang.injection.general.LanguageInjectionContributor;
import com.intellij.lang.injection.general.SimpleInjection;
import com.intellij.psi.PsiElement;
import com.kfyang.manualgear.daoplugin.simple.SimpleLanguage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.psi.*;

import static com.kfyang.manualgear.daoplugin.util.PsiUtils.inManualGear;

public class SimpleInjector implements LanguageInjectionContributor {
    @Override
    public @Nullable Injection getInjection(@NotNull PsiElement context) {
        if (shouldInjectSimple(context)) {
            return new SimpleInjection(SimpleLanguage.INSTANCE, "", "", null);
        }
        return null;
    }

    private static boolean shouldInjectSimple(PsiElement context) {
        if (!(context instanceof YAMLQuotedText && context.getParent() instanceof YAMLKeyValue keyValue)) {
            return false;
        }
        return (inSql(keyValue) || inFragSqlOrCond(keyValue)) && inManualGear(context);
    }

    // 注入到 sql 中
    private static boolean inSql(YAMLKeyValue keyValue) {
        return keyValue.getKeyText().equals("sql") && keyValue.getParent() instanceof YAMLMapping yamlMapping
            && yamlMapping.getParent() instanceof YAMLDocument;
    }

    // 注入到frag中
    private static boolean inFragSqlOrCond(YAMLKeyValue keyValue) {
        String keyText = keyValue.getKeyText();
        return (keyText.equals("sql") || keyText.equals("cond"))
            && keyValue.getParent() instanceof YAMLMapping fragMapping
            && fragMapping.getParent() instanceof YAMLSequenceItem sequenceItem
            && sequenceItem.getParent() instanceof YAMLSequence sequence
            && sequence.getParent() instanceof YAMLKeyValue frag
            && frag.getKeyText().equals("frags")
            && frag.getParent() instanceof YAMLMapping yamlMapping
            && yamlMapping.getParent() instanceof YAMLDocument;
    }


}
